export type ChannelType = {
  id: number;
  name: string;
};
const initialState = {
  allList: [] as ChannelType[],

  userList: [] as ChannelType[],
  currentId: 0,
};

export type ActionType =
  | { type: 'channel/saveAllList'; payload: ChannelType[] }
  | { type: 'channel/saveUserList'; payload: ChannelType[] }
  | { type: 'channel/delById'; payload: number }
  | { type: 'channel/add'; payload: ChannelType }
  | { type: 'channel/setCurrentId'; payload: number };

export default function channelReducer(
  state = initialState,
  action: ActionType
): typeof initialState {
  switch (action.type) {
    case 'channel/saveAllList':
      return { ...state, allList: [...action.payload] };
    case 'channel/saveUserList':
      return { ...state, userList: action.payload };
    case 'channel/delById':
      return {
        ...state,
        userList: state.userList.filter((item) => {
          return item.id !== action.payload;
        }),
      };

    case 'channel/add':
      return {
        ...state,
        userList: [...state.userList, action.payload].sort((item1, item2) => {
          return item1.id - item2.id;
        }),
      };
    case 'channel/setCurrentId':
      return {
        ...state,
        currentId: action.payload,
      };
    default:
      return state;
  }
}
